package org.jeecg.modules.manager.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manager.entity.DeletedEnum;
import org.jeecg.modules.manager.entity.GoodsType;
import org.jeecg.modules.manager.entity.SpareParts;
import org.jeecg.modules.manager.mapper.GoodsTypeMapper;
import org.jeecg.modules.manager.service.ISparePartsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 零配件表
 * @Author: jeecg-boot
 * @Date:   2021-11-19
 * @Version: V1.0
 */
@Slf4j
@Api(tags="零配件表")
@RestController
@RequestMapping("/manager/spareParts")
public class SparePartsController extends JeecgController<SpareParts, ISparePartsService> {
	@Autowired
	private ISparePartsService sparePartsService;
	@Autowired
	private GoodsTypeMapper goodsTypeMapper;


	/**
	 * 分页列表查询
	 *
	 * @param spareParts
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "零配件表-分页列表查询")
	@ApiOperation(value="零配件表-分页列表查询", notes="零配件表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SpareParts spareParts,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SpareParts> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("deleted",DeletedEnum.FALSE);
		Optional.ofNullable(spareParts.getSparePartsName()).ifPresent(s -> {
			queryWrapper.like("spare_parts_name",s);
		});

		Page<SpareParts> page = new Page<SpareParts>(pageNo, pageSize);
		IPage<SpareParts> pageList = sparePartsService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 @GetMapping(value = "/lists")
	 public Result<?> queryPageList() {
		 QueryWrapper<SpareParts> queryWrapper = new QueryWrapper<>();

		 BaseMapper<SpareParts> baseMapper = sparePartsService.getBaseMapper();
		 List<SpareParts> spareParts = baseMapper.selectList(queryWrapper);

		 Map<String, String> maps = goodsTypeMapper.selectList(new QueryWrapper<GoodsType>().eq("goods_type_parent_id", "4028b29e7d4c035c017d4c0381b90001"))
				 .stream().collect(Collectors.toMap(GoodsType::getId, GoodsType::getGoodsTypeName));

		 Map<String, List<SpareParts>> collect = spareParts.stream().collect(Collectors.groupingBy(SpareParts::getSparePartsTypeId));

		 synchronized (this){
			 for (String s : collect.keySet()) {
				 if (maps.get(s) == null){
					 System.out.println(s);
					 continue;
				 }
				 List<SpareParts> remove = collect.remove(s);
				 collect.put(maps.get(s),remove);
			 }
		 }


		 return Result.OK(collect);
	 }

	/**
	 * 添加
	 *
	 * @param spareParts
	 * @return
	 */
	@AutoLog(value = "零配件表-添加或修改")
	@ApiOperation(value="零配件表-添加或修改", notes="零配件表-添加或修改")
	@PostMapping(value = "/addOrEdit")
	public Result<?> add(@RequestBody SpareParts spareParts) {
		if (Optional.ofNullable(spareParts.getSparePartsId()).isPresent()){
			spareParts.setUpdatedBy(currentUser().getUsername());
			spareParts.setUpdatedTime(new Date());
			sparePartsService.updateById(spareParts);
			return Result.OK("修改成功！");
		}else {
			spareParts.setSparePartsId(UUIDGenerator.generate());
			spareParts.setCreatedBy(currentUser().getUsername());
			spareParts.setCreatedTime(new Date());
			sparePartsService.save(spareParts);
			return Result.OK("添加成功！");
		}
	}



	/**
	 * 通过id删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "零配件表-通过id批量删除")
	@ApiOperation(value="零配件表-通过id批量删除，id之间用逗号分隔", notes="零配件表-通过id批量删除，id之间用逗号分隔")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String ids) {
		return sparePartsService.removeIds(ids) != -1 ? Result.OK("删除成功!"):Result.error("删除失败");
	}


	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "零配件表-通过id查询")
	@ApiOperation(value="零配件表-通过id查询", notes="零配件表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SpareParts spareParts = sparePartsService.getById(id);
		return Result.OK(spareParts);
	}

  /**
   * 导出excel
   *
   * @param request
   * @param spareParts
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, SpareParts spareParts) {
      return super.exportXls(request, spareParts, SpareParts.class, "零配件表");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, SpareParts.class);
  }

}
